#if !defined(__WAVEFILE_H__)
#define __WAVEFILE_H__

#include <windows.h>

#include "MusicTime.h"

class AudioBuffer;

class WaveFile {
public:
    ~WaveFile();

    static WaveFile *create(const TCHAR *filename, unsigned int sampleRate, unsigned int numChannels, unsigned int bytesPerSample) throw();
    static WaveFile *open(const TCHAR *filename) throw();

    void unlink() throw();

    void write(const AudioBuffer *buffer) throw();
    void finalize() throw();

    void read(void *buffer, unsigned int bufferSize, unsigned long long startSample) throw();

    MusicTime length() const throw();

    unsigned int samplesPerSecond() const throw();
    unsigned int numChannels() const throw();
    unsigned int bytesPerSample() const throw();
private:
    WaveFile(const TCHAR *filename, bool write) throw();

    #pragma pack(push, 1)
    struct RiffHeader {
        char riff[4];
        unsigned int chunkSize;
        char wave[4];
    };
    struct FormatHeader {
        char fmt[4];
        unsigned int chunkSize;
        unsigned short format;
        unsigned short numChannels;
        unsigned int sampleRate;
        unsigned int byteRate;
        unsigned short blockAlign;
        unsigned short bitsPerSample;
    };
    struct DataHeader {
        char data[4];
        unsigned int chunkSize;
    };
    #pragma pack(pop)

    TCHAR m_filename[MAX_PATH];
    HANDLE m_hFile;
    unsigned int m_sampleRate;
    unsigned int m_numChannels;
    unsigned int m_bytesPerSample;
    unsigned int m_numSamples;

    DWORD m_dataStart;
};

#endif
